#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import urllib
import conf
import utils
import paper
import antispam
import xnuser
import permission
import papercomment
import paperbook
import adebook

class MainPage(webapp.RequestHandler):
    def get(self):
        #Do not need login for this page!
        cookieDict = utils.getXnCookieDict(self.request.cookies)        
        isLoggedIn = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        loginCallbackParams = urllib.urlencode({'url':callbackUrl})
        mathml = self.request.get('mathml')
        if isLoggedIn:
            try:
                xnuid = int(cookieDict['user'])
            except ValueError:
                xnuid = 0
        else:
            xnuid = 0

        errMsg = ''
        #Santinize param pid
        paperId = self.request.get('pid')
        try:
            paperId = int(paperId)
        except ValueError:
            paperId = 0
            errMsg = '缺少访问参数，请联系管理员'
        if paperId:
            paperModel = paper.readPaperById(paperId)
            if not paperModel:
                errMsg = '你要访问的文章不存在，可能已被删除'
        else:
            paperModel = None
            
        userName = '游客'
        userPhoto = conf.defaultXiaoneiTinyPhoto
        authorId = 0
        authorName = ''
        authorPhoto = ''
        title = ''
        content = ''
        category = ''
        catText = ''
        catNav = ''
        hasEditPaperPermission = False
        hasDeletePaperPermission = False
        lastModifiedTimeInLocalTimezone = ''
        commentList = []
        adebookList = []
        extraPaperInfo = {}
        if not errMsg and paperModel:
            authorId = paperModel.authorId
            if isLoggedIn:
                hasEditPaperPermission = permission.hasEditPaperPermission(xnuid, authorId)
                if not hasEditPaperPermission and paperModel.status != paper.paperStatusNormal:
                    errMsg = '你要访问的文章不存在，可能已被删除'
                hasDeletePaperPermission = permission.hasDeletePaperPermission(xnuid, authorId)
                userModel = xnuser.getAndUpdateUserData(xnuid, cookieDict.get('session_key'))
                if userModel:
                    userName = userModel.name
                    userPhoto = userModel.tinyurl_with_logo
            else:
                if paperModel.status != paper.paperStatusNormal:
                    errMsg = '你要访问的文章不存在，可能已被删除'
            authorUserModel = xnuser.getXnUserById(authorId)
            if authorUserModel:
                authorName = authorUserModel.name
                authorPhoto = authorUserModel.tinyurl_with_logo
            category = paperModel.category
            lastModifiedTimeInLocalTimezone = paperModel.lastModifiedTimeInLocalTimezone
            catText = utils.getCategoryTextByValue(category)
            catNav = utils.getCategoryNavByValue(category)
            title = paperModel.title
            if '1' == mathml:
                filteredContent = antispam.filter(paperModel.content, htmlEncodingMode=False, stripTagMode=False, outExtraInfo=extraPaperInfo, mathAmpDecodingMode=True)
            else:
                filteredContent = antispam.filter(paperModel.content, htmlEncodingMode=False, stripTagMode=True, outExtraInfo=extraPaperInfo)
                #get the first 100 characters
                filteredContent = filteredContent[0:100]
            if filteredContent == None:
                errMsg = '内容过滤出错，请联系管理员'
            else:
                content = filteredContent
                #hack ie: need an empty paragraph, or else it will be overridden
                content = content + '<p></p>'
                #list paper comments
                commentList = papercomment.listCommentsByPaperId(paperId)
                commenterIdList = []
                for commentModel in commentList:
                    if commentModel.commenterId not in commenterIdList:
                        commenterIdList.append(commentModel.commenterId)
                xnUserModelList = xnuser.getXnUserByIds(commenterIdList)
                commenterId2NamePhoto = {}
                for xnUserModel in xnUserModelList:
                    if xnUserModel.xnuid not in commenterId2NamePhoto:
                        commenterId2NamePhoto[xnUserModel.xnuid] = (xnUserModel.name, xnUserModel.tinyurl_with_logo)
                for commentModel in commentList:
                    if commentModel.commenterId in commenterId2NamePhoto:
                        commentModel.commenterName = commenterId2NamePhoto[commentModel.commenterId][0]
                        commentModel.commenterPhoto = commenterId2NamePhoto[commentModel.commenterId][1]
                    else:
                        commentModel.commenterName = str(commentModel.commenterId)
                        commentModel.commenterPhoto = ''
                    commentModel.hasDeleteCommentPermission = False
                    if isLoggedIn:
                        commentModel.hasDeleteCommentPermission = permission.hasDeletePaperCommentPermission(xnuid, commentModel.commenterId, authorId)
            #list ad ebooks
            if '1' != mathml:
                mappingModelList = paperbook.listAdebooksByPaper(paperId, 0, 3)
                if mappingModelList:
                    for mapping in mappingModelList:
                        adebookModel = adebook.readAdebookById(mapping.ebid)
                        if adebookModel:
                            adebookList.append(adebookModel)

        containsMathml = extraPaperInfo.get('containsMathml') or paperId == conf.sysPaperIdHowToInputFormula
        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'siteUrl': conf.siteUrl,
            'appEngineUrl': conf.appEngineUrl,
            'siteName': conf.siteName,
            'api_key':conf.api_key,
            'isLoggedIn': isLoggedIn,
            'loginCallbackParams': loginCallbackParams,
            'xnuid': xnuid,
            'userName': userName,
            'userPhoto': userPhoto,
            'hasEditPaperPermission': hasEditPaperPermission,
            'hasDeletePaperPermission': hasDeletePaperPermission,
            'pid': paperId,
            'authorId': authorId,
            'authorName': authorName,
            'authorPhoto': authorPhoto,
            'category': category,
            'catText': catText,
            'catNav': catNav,
            'title': title,
            'content': content,
            'extraPaperInfo': extraPaperInfo,
            'defaultMathmlLogo': conf.defaultMathmlLogo,
            'commentList': commentList,
            'lastModifiedTimeInLocalTimezone': lastModifiedTimeInLocalTimezone,
            'initialIframeHeight': 400,
            'navRssLink': '订阅',
            'sysPaperUrlFormulaNotDisplay': conf.sysPaperUrlFormulaNotDisplay,
            'sysPaperUrlCelebrating': conf.sysPaperUrlCelebrating,
            'sysPaperUrlFaq': conf.sysPaperUrlFaq,
            'sysPaperUrlSiteEvents': conf.sysPaperUrlSiteEvents,
            'sysPaperUrlHowToRss': conf.sysPaperUrlHowToRss,
            'containsMathml': containsMathml,
            'adebookList': adebookList,
            'errMsg': errMsg
        }
        if '1' == mathml:
            if paperId == conf.sysPaperIdHowToInputFormula:
                self.response.headers['Content-Type'] = 'text/xml; charset=utf-8'
                #self.response.headers['Content-Type'] = 'application/xhtml+xml'
                templatePage = 'pages/howtoformula.xml'
            else:
                if containsMathml:
                    self.response.headers['Content-Type'] = 'text/xml; charset=utf-8'
                    templatePage = 'pages/readpapermath.xml'
                else:
                    templatePage = 'pages/readpapernomath.html'
        else:
            templatePage = 'pages/readpaper.html'
        path = os.path.join(os.path.dirname(__file__), templatePage)
        self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/mathml/readpaper', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
